package main

import (
	"context"
	"log"
	"time"

	"example_shop/kitex_gen/example/shop/item"
	"example_shop/kitex_gen/example/shop/item/itemservice"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/kitex/client"
	"github.com/cloudwego/kitex/client/callopt"

	// "github.com/hertz-contrib/cache"
	// "github.com/hertz-contrib/cache/persist"
	etcd "github.com/kitex-contrib/registry-etcd"
)

var (
	cli itemservice.Client
)

func main() {
	// 使用时请传入真实 etcd 的服务地址，本例中为 127.0.0.1:2379
	resolver, err := etcd.NewEtcdResolver([]string{"127.0.0.1:3379"})
	if err != nil {
		log.Fatal(err)
	}

	// c, err := itemservice.NewClient("example.shop.item", client.WithHostPorts("0.0.0.0:8888"))
	c, err := itemservice.NewClient("example.shop.item", client.WithResolver(resolver))
	if err != nil {
		log.Fatal(err)
	}
	cli = c

	hz := server.New(server.WithHostPorts("0.0.0.0:8889"))

	// memoryStore := persist.NewMemoryStore(1 * time.Minute)
	// // 设置针对以 URI 为 Key 的缓存过期时间
	// hz.Use(cache.NewCacheByRequestURI(memoryStore, 1*time.Second))
	// 通过使用 WithCacheStrategyByRequest 自定义缓存策略，包括缓存的 Key、存储介质，以及过期时间。
	// hz.Use(cache.NewCache(
	// 	memoryStore,
	// 	time.Second,
	// 	cache.WithCacheStrategyByRequest(func(ctx context.Context, c *app.RequestContext) (bool, cache.Strategy) {
	// 		return true, cache.Strategy{
	// 			CacheKey: c.Request.URI().String(),
	// 		}
	// 	}),
	// ))

	hz.GET("/api/item", Handler)

	if err := hz.Run(); err != nil {
		log.Fatal(err)
	}
}

func Handler(ctx context.Context, c *app.RequestContext) {
	req := item.NewGetItemReq()
	req.Id = 1024
	resp, err := cli.GetItem(context.Background(), req, callopt.WithRPCTimeout(3*time.Second))
	if err != nil {
		log.Fatal(err)
	}

	// c.String(200, resp.String())
	c.JSON(200, map[string]interface{}{
		"item": resp.Item,
		"base": resp.BaseResp,
	})
}
